#include "dataprocess.h"
#include "cglobals.h"
#include <QRandomGenerator>

DataProcess::DataProcess(QObject *parent) : QObject(parent)
{
    pReceivedAllCyclesData = new QVector<QByteArray*>(RECEIVE_CYCLES_CAPACITY);
    pReceivedAllCyclesData->clear();
    pToolBarData = new QVector<pTOOLBAR_DATA>;
    pToolBarData->clear();
    pAllPagesData = new QVector<pPAGE_CONTEXT>;
    pAllPagesData->clear();
    pCyclesCount = new int(0);
    pCurrentPage = new int(1);
    pFormatSetting = new struct _format_settings;
    pCurvesList = new QVector<PDATA_CONTEXT>;
    pCurvesList->clear();
    pDataSource = new int(DATA_SOURCE::LOGFILE);

}

DataProcess::~DataProcess()
{

}

void DataProcess::updateReceivedCyclesData(QByteArray* pData)
{
    pReceivedAllCyclesData->push_back(pData);
    (*pCyclesCount)++;

    return;
}


// 所有页面数据初始化
void DataProcess::initAllPages(struct _format_settings* pFormatSetting)
{
    clearToolBarData();
    clearAllPagesData();

    setFormatSetting(pFormatSetting);

#ifdef DWORD
    // int count = 0;
    int lastVarEndByte = 0;              // 上一个变量的结束字节编号
#endif

    for (auto &item : std::as_const(*pFormatSetting->Body->Frame->Field)) {
        // 链表中不存在该数据显示的页面(新建), 将该页面放到链表同样的位置
        // 如果有Display属性，则不属于ToolBar里的数据
        if(item->Display)
        {
            if((int)*item->Display->Position->Page > pAllPagesData->count())
            {
                for(int i = pAllPagesData->count(); i < (int)*item->Display->Position->Page; ++i)
                {
                    pPAGE_CONTEXT pPageContext = new struct _page_context;
                    pPageContext->context = new QVector<PDATA_CONTEXT>;
                    pAllPagesData->push_back(pPageContext);
                }
            }

            PDATA_CONTEXT pSingleVarContext = new struct _data_context;
            pSingleVarContext->title = new QString(*item->Label);
            pSingleVarContext->allCyclesIntValues = NULL;
            pSingleVarContext->allCyclesStrValues = NULL;
            pSingleVarContext->blue = NULL;
            pSingleVarContext->column = NULL;
            pSingleVarContext->computationType = NULL;
            pSingleVarContext->currentCycleValue = NULL;
            pSingleVarContext->displayType = NULL;
            pSingleVarContext->enumeratedLabel = NULL;
            pSingleVarContext->green = NULL;
            pSingleVarContext->len = NULL;
            pSingleVarContext->max = NULL;
            pSingleVarContext->min = NULL;
            pSingleVarContext->red = NULL;
            pSingleVarContext->row = NULL;
            pSingleVarContext->show_flag = new bool(true);
            pSingleVarContext->start = NULL;
            pSingleVarContext->unit = NULL;
#ifdef DWORD
            // pSingleVarContext->bit_pos = NULL;
            pSingleVarContext->byteStart = NULL;
#endif

            if(item->Computation)
            {
                pSingleVarContext->computationType = new QString(*item->Computation->Type);
                pSingleVarContext->start = new int(*item->Computation->First_Bit_Position);
                pSingleVarContext->len = new int(*item->Computation->Bit_Count);

#ifdef DWORD
                // 整字节
                if (*pSingleVarContext->len % 8 == 0) {
                    lastVarEndByte = *pSingleVarContext->start / 8 + *pSingleVarContext->len / 8;
                } else {     //非整字节
                    if (*pSingleVarContext->start / 8 - lastVarEndByte < 2) {
                        if (pSingleVarContext->byteStart == nullptr) {
                            if (*pSingleVarContext->start / 8 - lastVarEndByte < 1) {       // DWORD的低字节
                                pSingleVarContext->byteStart = new int(*pSingleVarContext->start / 8);
                            } else {                                                         // DWORD的高字节
                                pSingleVarContext->byteStart = new int(*pSingleVarContext->start / 8 - 1);
                            }
                        }
                    }
                    else if(*pSingleVarContext->start / 8 - lastVarEndByte >= 2 && *pSingleVarContext->start / 8 - lastVarEndByte < 4){
                        lastVarEndByte += 2;
                        if (pSingleVarContext->byteStart == nullptr) {
                            if (*pSingleVarContext->start / 8 - lastVarEndByte < 1) {       // DWORD的低字节
                                pSingleVarContext->byteStart = new int(*pSingleVarContext->start / 8);
                            } else {                                                         // DWORD的高字节
                                pSingleVarContext->byteStart = new int(*pSingleVarContext->start / 8 - 1);
                            }
                        }
                    } else {
                        if (pSingleVarContext->byteStart == nullptr) {
                            lastVarEndByte = *pSingleVarContext->start / 8;
                        }
                    }

                }
                // if(pSingleVarContext->byteStart)qDebug()<<*pSingleVarContext->title << *pSingleVarContext->byteStart;

#endif
            }

            pSingleVarContext->displayType = new QString(*item->Display->Type);

            if(item->Display->Enumerated_Label)
            {
                pSingleVarContext->enumeratedLabel = new QString(*item->Display->Enumerated_Label);
            }

            pSingleVarContext->row = new int(*item->Display->Position->Row);
            pSingleVarContext->column = new int(*item->Display->Position->Column);

            if(item->Display->Range)
            {
                pSingleVarContext->max = new int(*item->Display->Range->Max);
                pSingleVarContext->min = new int(*item->Display->Range->Min);
            }

            if(item->Display->Unit)
            {
                pSingleVarContext->unit = new QString(*item->Display->Unit);
            }

            pAllPagesData->at((int)*item->Display->Position->Page - 1)->context->append(pSingleVarContext);
        }


        // 如果只有Computation属性，则属于ToolBar里的数据
        if(!item->Display && item->Computation)
        {
            pTOOLBAR_DATA pTempToolbardata = new struct _tool_bar_data;
            pToolBarData->push_back(pTempToolbardata);
            pTempToolbardata->start = new unsigned int(*item->Computation->First_Bit_Position);
            pTempToolbardata->len = new unsigned int(*item->Computation->Bit_Count);
            pTempToolbardata->title = new QString(*item->Label);
        }
    }

    return;

}


// 设置数据来源
void DataProcess::setDataSource(int* pDataSource)
{
    this->pDataSource = pDataSource;

    return;
}

void DataProcess::printPage()
{
    for(int i=0; i< pAllPagesData->count(); ++i)
    {
        for (auto &item : std::as_const(*(*pAllPagesData)[i]->context)) {
            qDebug()<< *item->title;
        }
    }

    return;
}

int DataProcess::getCyclesCount()
{
    return *pCyclesCount;
}

QByteArray DataProcess::getPauseData(int cycle)
{
//    return *(pPauseData->at(cycle - 1));
    return *(pReceivedAllCyclesData->at(cycle - 1));
}

void DataProcess::setPause()
{
//    if (NULL == pPauseData)  pPauseData = new QVector<QByteArray*>;

    pauseFlag = true;

    for(auto &item : std::as_const(*pCurvesList))
    {
        item->allCyclesIntValues->clear();
        item->allCyclesStrValues->clear();
    }

    foreach(QByteArray* byte, *pReceivedAllCyclesData) {
//        pPauseData->push_back(byte);

        for (auto &item : std::as_const(*pCurvesList)) {
            addDataToCurvesList(byte->toHex().toBase64(), item);

        }
    }
    return;

}

void DataProcess::resume()
{
    pauseFlag = false;
    for (auto &item : std::as_const(*pCurvesList)) {
        item->allCyclesIntValues->clear();
        item->allCyclesStrValues->clear();

    }

    return;
}

/* 获取子串
 * 说明：如果是整字节转化，则是截取的字串是16进制数，如果是非整字节转化，则获取的是二进制数
*/
STRVALUE DataProcess::getSubStrFromString(QString str, quint32 start, quint8 len, bool bigEndian)
{
    /*
     根据起始偏移位计算字符串中截取位置(从16进制形式的字符串截取的位置)以及截取的长度
     原则：
     1. 如果起始位置是满字节（即：起始位偏移能被WORD_LEN整除），则起始位置即为起始位偏移 / WORD_LEN，
         数据读取完成后，起始位置偏移1个数据长度(1个字节的16进制字符占2个字符长度，因此数据长度为(WORD_LEN / 8) * 2);
         a) 如果数据长度为满字节（即能被8整除），数据截取长度为字节长度;
         b) 如果数据长度不是满字节，数据截取长度为字节长度+1;
            1) 需要计算转为二进制形式的字符串后的截取起始位置和截取长度。
     2. 如果起始位置不是满字节（即：起始位偏移能被8整除），则起始位置仍然为位偏移/8，
          但是需要计算截取长度时需要+1，数据读取完成后，起始偏移位置不变（要求协议中起始位置不是满字节的，
          偏移不超过1个字节）
          a) 需要计算转为二进制形式的字符串后的截取起始位置和截取长度。
     */

    STRVALUE res;
    quint32 pos = (start / 8) * 2;                                  // 16进制字符串数据的截取起始字节位置
    quint8 bytes_length = len / 8;                                  // 16进制字符串数据长度(字节)
    quint8 bytes_offset = len % 8;                                  // 在截取后的16进制数据转换成二级制后的数据长度
    qint8 tBinStart = 8 - (start % 8 + len);                        // 在截取后的16进制数据转换成二进制后的起始位置

//    if (0 != bytes_offset) bytes_length += 1;
    bytes_length +=  0 != bytes_offset ? 1 : 0;

    if (0 == start % 8) {   // 起始位置为整字节的开头

        if (0 == bytes_offset && 1 <= bytes_length) {   // 起始为整字节开头，数据长度为单个或多个整字节

            // 根据大小端Endign进行计算
            res.value = bigEndian ? str.mid(pos, bytes_length * 2) : toBigEndian(str.mid(pos, bytes_length * 2));
            res.type = "HEX";
        }
        if (0 != bytes_offset) {      // 起始为整字节开头，数据长度不到1个字节
            QString tBinaryString;

            // 根据大小端Endign进行计算
            tBinaryString = bigEndian ? hexToBin(str.mid(pos, bytes_length * 2)) : hexToBin(toBigEndian(str.mid(pos, bytes_length * 2)));
            res.value = tBinaryString.mid(tBinStart, len) ;
            res.type = "BIN";
        }
    }

    if (0 != start % 8) {   // 起始位置不是整字节的开头

        if (0 < (start % 8 + len) / 8 && 0 != (start % 8 + len) % 8) {      // 起始不是整字节开头，数据长度不到1个字节(跨字节)
            QString tBinaryString;
            // big endian

            // 根据大小端Endign进行计算
            tBinaryString = bigEndian ? hexToBin(str.mid(pos, (bytes_length + 1) * 2)) : hexToBin(toBigEndian(str.mid(pos, (bytes_length + 1) * 2)));

//            if (bigEndian) tBinaryString = hexToBin(str.mid(pos, (bytes_length + 1) * 2));
//            // little endian
//            if (!bigEndian) tBinaryString = hexToBin(toBigEndian(str.mid(pos, (bytes_length + 1) * 2)));
            res.value = tBinaryString.mid(tBinStart + 8, len);
            res.type = "BIN";
        }

        if (0 == (start % 8 + len) / 8 || (0 < (start % 8 + len) / 8 && 0 == (start % 8 + len) % 8)) {      // 起始不是整字节开头，数据长度不到1个字节(未跨字节)
            QString tBinaryString;

            // 根据大小端Endign进行计算
            tBinaryString = bigEndian ? hexToBin(str.mid(pos, bytes_length * 2)) : hexToBin(toBigEndian(str.mid(pos, bytes_length * 2)));

//            // big endian
//            if (bigEndian) tBinaryString = hexToBin(str.mid(pos, bytes_length * 2));
//            // little endian
//            if (!bigEndian) tBinaryString = hexToBin(toBigEndian(str.mid(pos, bytes_length * 2)));
            res.value = tBinaryString.mid(tBinStart, len);
            res.type = "BIN";
        }

    }

    return res;
}

STRVALUE DataProcess::getDWORDSubStrFromString(QString str, quint32 start, quint32 bitStart, quint8 len, bool bigEndian)
{
    /*
     根据起始偏移位计算字符串中截取位置(从16进制形式的字符串截取的位置)以及截取的长度
     原则：
     1. 如果起始位置是满字节（即：起始位偏移能被WORD_LEN整除），则起始位置即为起始位偏移 / WORD_LEN，
         数据读取完成后，起始位置偏移1个数据长度(1个字节的16进制字符占2个字符长度，因此数据长度为(WORD_LEN / 8) * 2);
         a) 如果数据长度为满字节（即能被8整除），数据截取长度为字节长度;
         b) 如果数据长度不是满字节，数据截取长度为字节长度+1;
            1) 需要计算转为二进制形式的字符串后的截取起始位置和截取长度。
     2. 如果起始位置不是满字节（即：起始位偏移能被8整除），则起始位置仍然为位偏移/8，
          但是需要计算截取长度时需要+1，数据读取完成后，起始偏移位置不变（要求协议中起始位置不是满字节的，
          偏移不超过1个字节）
          a) 需要计算转为二进制形式的字符串后的截取起始位置和截取长度。
     */


    STRVALUE res;
    quint32 pos = start * 2;                                        // 16进制字符串数据的截取起始字节位置
    quint8 bytes_length = 2;                                  // 16进制字符串数据长度(字节)
    quint8 bitOffset = 15 - (bitStart - start * 8) - len + 1;


    // 根据大小端Endign进行计算
    QString tBinaryString = bigEndian ? hexToBin(str.mid(pos, bytes_length * 2)) : hexToBin(toBigEndian(str.mid(pos, bytes_length * 2)));
    res.value = tBinaryString.mid(bitOffset, len);
    res.type = "BIN";

    return res;
}

QDateTime DataProcess::getDateTimeFromData(QByteArray data, struct _format_settings* pFormatSetting)
{
    // 数据转换为字符串
#ifdef BASE64
    QString buf = QByteArray::fromBase64(data).toStdString().data();
#endif

#ifdef RAWDATA
    QString buf = QString::fromUtf8(data.toHex());
#endif

#ifdef HEXDATA
    QString buf = QString::fromUtf8(data);
#endif

    QDateTime tDateTime;
    quint32 year = 0;
    quint32 month = 0;
    quint32 day = 0;
    quint32 hour = 0;
    quint32 minute = 0;
    quint32 second = 0;

    //开始解析时间
    for (auto &item : std::as_const(*pFormatSetting->Body->Frame->Field)) {
        if (!item->Display && item->Computation){
           //
            STRVALUE str;
            if (*pFormatSetting->Body->Frame->Endian == "Little") {
                str = getSubStrFromString(buf, *item->Computation->First_Bit_Position, *item->Computation->Bit_Count);
            } else {
                str = getSubStrFromString(buf, *item->Computation->First_Bit_Position, *item->Computation->Bit_Count, true);
            }

            // 获取转换的进制
            int system_type = MAP_DISPLAY_TYPE.value(str.type.toUpper());
            switch(MAP_TOOLBAR_STRING.value(item->Label->toUpper())) {
            case 1:
                year = str.value.toUInt(NULL, system_type);
                break;

            case 2:
                month = str.value.toUInt(NULL, system_type);
                break;

            case 3:
                day = str.value.toUInt(NULL, system_type);
                break;

            case 4:
                hour = str.value.toUInt(NULL, system_type);
                break;

            case 5:
                minute = str.value.toUInt(NULL, system_type);
                break;

            case 6:
                second = str.value.toUInt(NULL, system_type);
                break;

            default:
                break;

        }
        }

    }

    tDateTime.setDate(QDate(year, month, day));
    tDateTime.setTime(QTime(hour, minute, second));

    return tDateTime;
}



// 解码时间
void DataProcess::decodeToolBarData(QByteArray data)
{
    // 数据转换为字符串
#ifdef BASE64
        QString buf = QByteArray::fromBase64(data).toStdString().data();

#endif

#ifdef RAWDATA
        QString buf = QString::fromUtf8(data.toHex());
#endif

#ifdef HEXDATA
        QString buf = QString::fromUtf8(data);
#endif

#ifdef TWO_NUMBERS
    QString year("20");
#else
    QString year;
#endif

    //开始解析周期和时间
    for(int n = 0; n < pToolBarData->count(); ++n)
    for(auto &item : std::as_const(*pToolBarData))
    {
        item->showValue = new QString;
        item->showValue->clear();

        STRVALUE str;
        if (*pFormatSetting->Body->Frame->Endian == "Little") {
            str = getSubStrFromString(buf, *item->start, *item->len);
        } else {
            str = getSubStrFromString(buf, *item->start, *item->len, true);
        }


        // 获取转换的进制
        int system_type = MAP_DISPLAY_TYPE.value(str.type.toUpper());

        switch (MAP_TOOLBAR_STRING.value(item->title->toUpper())) {
        case 0:
            item->showValue->append(QString::number(str.value.toUInt(NULL, system_type),10));
            break;

        case 1:
            item->showValue->append(year + QString("%1").arg(str.value.toUInt(NULL, system_type), 2, 10, QLatin1Char('0')));
            break;

        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        {
            item->showValue->append(QString("%1").arg(str.value.toUInt(NULL, system_type), 2, 10, QLatin1Char('0')));
            break;
        }

//         case 7:
//             item->showValue->append(QString("%1").arg(str.value.toUInt(NULL, system_type), 3, 10, QLatin1Char('0')));
// //            qDebug()<< buf ;
// //            qDebug()<<*item->start;
// //            qDebug()<<*item->len;
//             break;

        default:
            break;
        }
    }
    return;
}


// 解码页面数据
pPAGE_CONTEXT DataProcess::decodePageDatas(QByteArray data)
{
    // 数据转换为字符串
#ifdef BASE64
        QString buf = QByteArray::fromBase64(data).toStdString().data();
#endif

#ifdef RAWDATA
        QString buf = QString::fromUtf8(data.toHex());
#endif

#ifdef HEXDATA
        QString buf = QString::fromUtf8(data);
#endif

    // 获取枚举类型列表
    QVector<struct _enumerated*>* Enumerated = pFormatSetting->Body->Enumerated;

    if(*pCurrentPage <= 0)
    {
        return NULL;
    }

    pPAGE_CONTEXT page_data = pAllPagesData->at(*pCurrentPage - 1);

    // 开始解析页面内容
    for(auto &item : std::as_const(*page_data->context)) {
        if(0 == item->displayType->compare(STRING_DISPLAY_TYPE_TITLE))
        {
            continue;
        }

        STRVALUE value;

        if (*pFormatSetting->Body->Frame->Endian == "Little") {
            // 不需要截取DWORD双字节
            if (item->byteStart == NULL) {
                value = getSubStrFromString(buf, *item->start, *item->len);
            } else {
                value = getDWORDSubStrFromString(buf, *item->byteStart, *item->start, *item->len);
            }

        } else {
            // 不需要截取DWORD双字节
            if (item->byteStart == NULL) {
                value = getSubStrFromString(buf, *item->start, *item->len, true);
            } else {
                value = getDWORDSubStrFromString(buf, *item->byteStart, *item->start, *item->len, true);
            }
        }

        QString tmp_data = getDisplayString(value, item, Enumerated);


        // 添加单位
//        if (item->unit) tmp_data += *item->unit;
        tmp_data += item->unit ? *item->unit : "";

        // 添加数据
        if(!item->currentCycleValue)                                                                                       // 新增
        {
            item->currentCycleValue = new QString(tmp_data);
        }
        else                                                                                                                // 修改
        {
            item->currentCycleValue->clear();
            item->currentCycleValue->append(tmp_data);
        }

    }

    return page_data;
}




// 解码单个数据
void DataProcess::addDataToCurvesList(QByteArray data, PDATA_CONTEXT pSingleVarData)
{
    if(pSingleVarData == NULL) return;

     // 数据转换为字符串
#ifdef BASE64
    QString buf = QByteArray::fromBase64(data).toStdString().data();
#endif

#ifdef RAWDATA
    QString buf = QString::fromUtf8(data.toHex());
#endif

#ifdef HEXDATA
    QString buf = QString::fromUtf8(data);
#endif

    // 获取枚举类型列表
    QVector<struct _enumerated*>* Enumerated = pFormatSetting->Body->Enumerated;

    STRVALUE value;
    if (*pFormatSetting->Body->Frame->Endian == "Little") {
        // 不需要截取DWORD双字节
        if (pSingleVarData->byteStart == NULL) {
            value = getSubStrFromString(buf, *pSingleVarData->start, *pSingleVarData->len);
        } else {
            value = getDWORDSubStrFromString(buf, *pSingleVarData->byteStart, *pSingleVarData->start, *pSingleVarData->len);
        }
    } else {
        // 不需要截取DWORD双字节
        if (pSingleVarData->byteStart == NULL) {
            value = getSubStrFromString(buf, *pSingleVarData->start, *pSingleVarData->len, true);
        } else {
            value = getDWORDSubStrFromString(buf, *pSingleVarData->byteStart, *pSingleVarData->start, *pSingleVarData->len, true);
        }
    }



    QString tmp_display_data = getDisplayString(value, pSingleVarData, Enumerated);

    qint32 intValue = getDrawValue(value, pSingleVarData);

     // 添加单位
//     if(pSingleVarData->unit)
//     {
//         tmp_display_data += *pSingleVarData->unit;
//     }
     tmp_display_data += pSingleVarData->unit ? *pSingleVarData->unit : "";

     // 添加数据
     if(!pSingleVarData->allCyclesIntValues)
     {
         pSingleVarData->allCyclesIntValues = new QVector<int*>(CYCLES_CAPACITY);
         pSingleVarData->allCyclesIntValues->clear();
     }

     pSingleVarData->allCyclesIntValues->push_back(new int(intValue));

     if(!pSingleVarData->allCyclesStrValues)
     {
         pSingleVarData->allCyclesStrValues = new QVector<QString*>(CYCLES_CAPACITY);
         pSingleVarData->allCyclesStrValues->clear();
     }
     pSingleVarData->allCyclesStrValues->push_back(new QString(tmp_display_data));

     return;
}



void DataProcess::msgProcessSlot(QByteArray* pData)
{
#ifdef BASE64
    decodeToolBarData(pData->toHex().toBase64());
    if (!pauseFlag)
    emit pageDataProcessed(getCycleNumber(), getCycleTime(), decodePageDatas(pData->toHex().toBase64()));

    if(*pDataSource == DATA_SOURCE::UDP && !pauseFlag)
    {
        for (auto &item : std::as_const(*pCurvesList)) {
            addDataToCurvesList(pData->toHex().toBase64(), item);
        }
    }
#endif

#ifdef RAWDATA
    decodeToolBarData(*pData);
    emit pageDataProcessed(getCycleNumber(), getCycleTime(), decodePageDatas(*pData));

    if(*pDataSource == DATA_SOURCE::UDP)
    {
        for (auto &item : std::as_const(*pCurvesList)) {
            addDataToCurvesList(*pData, item);
        }
    }
#endif

#ifdef HEXDATA
    decodeToolBarData(pData->toHex());
    emit pageDataProcessed(getCycleNumber(), getCycleTime(), decodePageDatas(pData->toHex()));

    if(*pDataSource == DATA_SOURCE::UDP)
    {
        for (auto &item : std::as_const(*pCurvesList)) {
            addDataToCurvesList(pData->toHex(), item);
        }
    }
#endif

    updateReceivedCyclesData(pData);

    return;
}



// 设置当前页码
void DataProcess::setCurrentPage(int page)
{
    *pCurrentPage = page;
}

// 保存日志
void DataProcess::saveLogToFile(QString filePath)
{
    if(NULL == pReceivedAllCyclesData) return;

    QFile logfile(filePath);
    logfile.open(QIODevice::WriteOnly);
    QDataStream out(&logfile);

    for(int i = 0; i < pReceivedAllCyclesData->size(); ++i)
    {
#ifdef BASE64
        out<<pReceivedAllCyclesData->at(i)->toHex().toBase64();
#endif

#ifdef RAWDATA
        out<<*pReceivedAllCyclesData->at(i);
#endif

#ifdef HEXDATA
        out<<pReceivedAllCyclesData->at(i)->toHex();
#endif
    }

    logfile.close();
    *pCyclesCount = 0;                                                                                            // 写入总周期数清0

    clearReceivedDatas();

    return;
}


// 添加曲线
PDATA_CONTEXT DataProcess::addCurve(QString name)
{
//    for(int n = 0; n < pAllPagesData->count(); ++n)
    for(auto &item : std::as_const(*pAllPagesData))
    {
        for (auto &sub_item : std::as_const(*item->context)) {
            if(0 == name.compare(*sub_item->title))
            {
                if(STRING_DISPLAY_TYPE_TITLE == *sub_item->displayType) return NULL;       // 如果添加的曲线的显示类型是标题，则直接返回
                sub_item->red = new int(QRandomGenerator::global()->generate() % 256);
                sub_item->green = new int(QRandomGenerator::global()->generate() % 256);
                sub_item->blue = new int(QRandomGenerator::global()->generate() % 256);
                sub_item->show_flag = new bool(true);
                if(sub_item->allCyclesIntValues)
                {
                    QVector<int*>().swap(*sub_item->allCyclesIntValues);
                }
                if(sub_item->allCyclesStrValues)
                {
                    QVector<QString*>().swap(*sub_item->allCyclesStrValues);
                }
                pCurvesList->append(sub_item);
                return sub_item;
            }
        }

    }
    return NULL;

}


// 删除曲线
void DataProcess::delCurve(QString name)
{
//    for(int n = 0; n < pAllPagesData->count(); ++n)
    for(auto &item : std::as_const(*pAllPagesData))
    {
        for (auto &sub_item : std::as_const(*item->context)) {
            if(0 == name.compare(*sub_item->title))
            {
                pCurvesList->removeOne(sub_item);
                return;
            }
        }
    }

    return;
}


// 获取绘图列表
QVector<PDATA_CONTEXT>* DataProcess::getCurvesList()
{
    return pCurvesList;
}

// 清空绘图列表
void DataProcess::clearCurvesList()
{
    if(false == pCurvesList->isEmpty())
    {
        pCurvesList->clear();
    }

    return;
}


// 获取周期号
QString DataProcess::getCycleNumber()
{
//    for(int n = 0; n < pToolBarData->count(); ++n)
    for(auto &item : std::as_const(*pToolBarData))
    {
        if(0 == item->title->compare(STRING_LABEL_CYCLE_NUMBER))
        {
            return *item->showValue;
        }
    }
    return QString("");
}




// 获取周期时间
QString DataProcess::getCycleTime()
{
    QString time;
    time.clear();
//    for(int n = 0; n < pToolBarData->count(); ++n)
    for(auto &item : std::as_const(*pToolBarData))
    {
        switch (MAP_TOOLBAR_STRING.value(item->title->toUpper())) {
        case 1:   // year
        {
            time.append(*item->showValue);
            break;
        }

        case 2:   // month
        {
            time.append(YEAR_SEPARATOR);
            time.append(*item->showValue);
            break;
        }

        case 3:   // day
        {
            time.append(YEAR_SEPARATOR);
            time.append(*item->showValue);
            break;
        }

        case 4:   // hour
        {
            time.append(YEAR_TIME_SEPARATOR);
            time.append(*item->showValue);
            break;
        }

        case 5:     // minitues
        {
            time.append(TIME_SEPARATOR);
            time.append(*item->showValue);
            break;
        }

        case 6:     // second
        {
            time.append(TIME_SEPARATOR);
            time.append(*item->showValue);
            break;
        }

        // case 7:     // millisecond
        // {
        //     time.append(MILLISECOND_SEPARATOR);
        //     time.append(*item->showValue);
        //     break;
        // }

        default:
            break;
        }
    }

    return time;
}



// 设置格式
void DataProcess::setFormatSetting(struct _format_settings* pFormatSetting)
{
    this->pFormatSetting = pFormatSetting;

    return;
}


// 清空所有页数据
void DataProcess::clearAllPagesData()
{
    if(NULL == pAllPagesData)
    {
        return;
    }

    for (auto &item : std::as_const(*pAllPagesData)) {
        deleteStruct_page_context(item);
    }

    pAllPagesData->clear();

    return;
}

void DataProcess::clearToolBarData()
{
    if(NULL == pToolBarData)
    {
        return;
    }


    for(auto &item : std::as_const(*pToolBarData))
    {
        deleteStruct_tool_bar_data(item);
    }

    pToolBarData->clear();

    return;
}



// 清空所有接收到的udp数据
void DataProcess::clearReceivedDatas()
{
    if(NULL == pReceivedAllCyclesData) return;

    qDeleteAll(pReceivedAllCyclesData->begin(), pReceivedAllCyclesData->end());
    pReceivedAllCyclesData->clear();

    return;
}










